/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.tenant.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.moon.framework.autoconfigure.config.SystemConfig;
import org.moon.framework.autoconfigure.datasource.routing.DynamicDataSourceContextHolder;
import org.moon.framework.autoconfigure.secure.AuthUtils;

/**
 * 动态数据源（多租户）
 * @author moon
 */
@Aspect
public class TenantDataSourceAnnotationAspect implements ITenantAspect{

    private SystemConfig systemConfig;

    public  TenantDataSourceAnnotationAspect(SystemConfig systemConfig){
        this.systemConfig = systemConfig;
    }

    @Pointcut(
            "(@annotation(org.moon.framework.autoconfigure.tenant.annotation.TenantDS) || @within(org.moon.framework.autoconfigure.tenant.annotation.TenantDS))"
    )
    public void dsPointCut() {

    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        changeDataSourceByName(AuthUtils.getTenantCode(),systemConfig.getApplicationName());
        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}
